package RoleService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"time"
)

func Add(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	data := r.GetMap()
	data["create_at"] = time.Now().Unix()
	// 增加附加数据
	if req.AddInsertData != nil {
		otherData := req.AddInsertData(r)
		for k, v := range otherData {
			data[k] = v
		}
	}
	// 添加前方法
	if req.AddBeforeFn != nil {
		respRes := req.AddBeforeFn(r, data)
		if respRes.Code != 0 {
			return respRes
		}
	}
	tx, err := g.DB().Ctx(ctx).Begin()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	obj := tx.Table(req.TableName).Unscoped()
	res, err := obj.Fields(obj.GetFieldsStr()).Insert(data)
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}
	id, err := res.LastInsertId()
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}
	// 删除原来的 sys_role_department
	_, err = tx.Table("sys_role_department").Where(
		"role_id", id).Delete()
	if err != nil {
		tx.Rollback()
		return response.FailByRequestMessage(nil, err.Error())
	}
	menuIdList := r.GetArray("menuIdList")
	// 插入 sys_role_department
	rmData := g.List{}
	for _, item := range menuIdList {
		rmData = append(rmData, g.Map{
			"role_id": id,
			"menu_id": item,
		})
	}
	if len(rmData) > 0 {
		res, err = tx.Model("sys_role_menu").Insert(rmData)
		if err != nil {
			tx.Rollback()
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	departmentIdList := r.GetArray("departmentIdList")
	// 插入 sys_role_department
	rdData := g.List{}
	for _, item := range departmentIdList {
		rdData = append(rdData, g.Map{
			"role_id":       id,
			"department_id": item,
		})
	}
	if len(rdData) > 0 {
		res, err = tx.Model("sys_role_department").Insert(rdData)
		if err != nil {
			tx.Rollback()
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	tx.Commit()
	return response.SuccessByRequestMessageData(nil, "添加成功", g.Map{
		"id": id,
	})
}
